﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace GoodStuff.Validation
{
    /// <summary>
    /// Facade pattern and Extension methods
    /// </summary>
    public static class Validator
    {
        public static ValidationResults Validate<T>(T target) where T : class
        {
            IRuleBuilder<T> validator = ValidationFactory.CreateValidator<T>();
            return validator.Validate(target);
        }

        public static void Assert<T>(T target) where T : class
        {
            IRuleBuilder<T> validator = ValidationFactory.CreateValidator<T>();
            validator.Assert(target);
        }

        public static ValidationResults Validate<T>(this IRuleBuilder<T> validator, T target) where T : class
        {
            ValidationResults results = new ValidationResults();

            foreach (IValidationRule<T> rule in validator.GetRules())
            {
                rule.Validate(target);
                if (!rule.IsValid)
                {
                    results.Errors.Add(new ValidationError(rule.ErrorMessage));
                }
            }
            return results;
        }

        public static void Assert<T>(this IRuleBuilder<T> validator, T target) where T : class
        {
            var results = Validate(target);
            if (!results.IsValid)
            {
                throw new ValidationException(results);
            }
        }
    }
}
